import { check } from "@tauri-apps/plugin-updater";
import { relaunch } from "@tauri-apps/plugin-process";
export default () => {
 
  const message =  window.$message
  const dialog = window.$dialog

  const checkV = async () => {
    return await check()
      .then((e: any) => {
        if (!e?.available) {
          return;
        }
        return {
          version: e.version,
          meg: `新版本 ${e.version} ,发布时间： ${e.date} 升级信息： ${e.body}`,
        };
      })
      .catch((e) => {
        console.error("检查更新错误，请稍后再试 " + e);
      });
  };

  const updater = async () => {
    dialog.success({
      title: "系统提示",
      content: "您确认要更新吗 ?",
      positiveText: "更新",
      negativeText: '不更新',
      maskClosable: false,
      closable: false,
      onPositiveClick: async () => {
          message.success("正在下载更新，请稍等");
  
          await check()
            .then(async (e: any) => {
              if (!e?.available) {
                return;
              }
              await e.downloadAndInstall((event: any) => {
                switch (event.event) {
                  case "Started":
                    message.success("文件大小：" + event.data.contentLength ? event.data.contentLength : 0);
                    break;
                  case "Progress":
                    message.success("正在下载" + event.data.chunkLength);
                    break;
                  case "Finished":
                    message.success("安装包下载成功，10s后重启并安装");
                    setTimeout(async () => {
                      await relaunch();
                    }, 10000);
                    break;
                }
              });
            })
            .catch((e) => {
              console.error("检查更新错误，请稍后再试 " + e);
            });
        
      },
      onNegativeClick: () => {
        message.info('您已取消更新')
      }
    })
    
  };

  return {
    checkV,
    updater,
  };
};
